package lowijs.XfDroid;

import java.util.*;

import android.app.*;
import android.content.*;
import android.graphics.*;
import android.os.*;
import android.preference.*;
import android.view.*;
import android.view.ContextMenu.*;
import android.widget.*;
import android.widget.AdapterView.*;
import android.widget.CompoundButton.*;
import android.net.*;

import lowijs.XfireClient.*;
import lowijs.XfireClient.event.*;
import lowijs.XfireClient.util.FriendComparator;

public class Friendslist extends ListActivity implements XfireObserver {
	private final XfireClient xfc = XfDroidService.getXfireClient();
	private final FriendManager fm = FriendManager.getInstance();
	
	private FriendslistAdapter adapter = null;
	private AlertDialog ad = null;
	private ListView lv = null;
	private SharedPreferences prefs = null;
	
	public void onCreate(Bundle b) {
		super.onCreate(b);
		setContentView(R.layout.friendslist);
		
		adapter = new FriendslistAdapter(getBaseContext(),
				R.layout.friendrow, fm.getOnlineFriends());
		setListAdapter(adapter);
		setupTitle();
		
		lv = getListView();
		
		View.OnCreateContextMenuListener listener =
			new View.OnCreateContextMenuListener() {
				public void onCreateContextMenu(ContextMenu menu, View v,
						ContextMenuInfo menuInfo) {
					getMenuInflater().inflate(
							R.menu.menu_friendslist_context, menu);
					int pos = ((AdapterContextMenuInfo)menuInfo).position;
					Friend f = adapter.getItem(pos);
					menu.setHeaderTitle(f.getNick());
				}
			};
		lv.setOnCreateContextMenuListener(listener);
		
		prefs = PreferenceManager.getDefaultSharedPreferences(this);
	}

	private void setupTitle() {
		setTitle("XfDroid : "
				+ xfc.getNickname() + " : " + xfc.getStatusText());
	}
	
	public void onStart() {
		EventManager.addObserver(this);
		friendslistHandler.sendEmptyMessage(0);
		XfDroidService.sendAllNotifications();
		super.onStart();
	}
	
	public void onStop() {
		EventManager.removeObserver(this);
		
		if (ad != null)
			ad.dismiss();
		
		super.onStop();
	}
	
	public void onSaveInstanceState(Bundle b) {
		if (ad != null && ad.isShowing()) {
			EditText etNickname = (EditText)ad.findViewById(R.id.etNickname);
			if (etNickname != null) {
				b.putBoolean("adSetNickname", true);
				b.putString("adNick", etNickname.getText().toString());
			}
			
			CheckBox cbAfk = (CheckBox)ad.findViewById(R.id.cbAfk);
			EditText etStatusText =
				(EditText)ad.findViewById(R.id.etStatusText);
			if (cbAfk != null && etStatusText != null) {
				b.putBoolean("adSetStatus", true);
				b.putBoolean("adAfk", cbAfk.isChecked());
				b.putString("adStatusText", etStatusText.getText().toString());
			}
		}
		super.onSaveInstanceState(b);
	}
	
	public void onRestoreInstanceState(Bundle b) {
		if (b.getBoolean("adSetNickname")) {
			showSetNickDialog(b.getString("adNick"));
			b.remove("adNick");
			b.remove("adSetNickname");
		} else if (b.getBoolean("adSetStatus")) {
			showSetStatusDialog(b.getString("adStatusText"),
					b.getBoolean("adAfk"));
			b.remove("adStatusText");
			b.remove("adAfk");
			b.remove("adSetStatus");
		}
		super.onRestoreInstanceState(b);
	}
	
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK)
			return true;
		return super.onKeyDown(keyCode, event);
	}

	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.menu_friendslist, menu);
		return true;
	}

	public boolean onOptionsItemSelected(MenuItem item) {
		switch(item.getItemId()) {
		case R.id.menu_friendslist_logoff:
			Intent i = new Intent(this, XfDroidService.class);
			stopService(i);
			return true;
		case R.id.menu_friendslist_setnick:
			showSetNickDialog(xfc.getNickname());
			return true;
		case R.id.menu_friendslist_setstatus:
			showSetStatusDialog(xfc.getStatusText(), false);
			return true;
		case R.id.menu_friendslist_profile:
			showBrowserFor("http://xfire.com/profile/" + xfc.getUsername());
			return true;
		case R.id.menu_friendslist_preferences:
			startActivity(new Intent(this, XfDroidPrefs.class));
			return true;
		}
		return false;
	}
	
	public boolean onContextItemSelected(MenuItem item) {
		final Friend f = adapter.getItem(((AdapterContextMenuInfo)item.getMenuInfo()).position);
		
		switch(item.getItemId()) {
		case R.id.menu_friendslist_context_viewprofile:
			showBrowserFor("http://xfire.com/profile/" + f.getUsername());
			return true;
		case R.id.menu_friendslist_context_viewscreens:
			ConnectivityManager cm = (ConnectivityManager)getSystemService(CONNECTIVITY_SERVICE);
			
			DialogInterface.OnClickListener listener = 
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						showScreenshotsFor(f);					
					}
				};
			
			ad = new AlertDialog.Builder(this)
			.setTitle(R.string.warning)
			.setIcon(android.R.drawable.ic_dialog_alert)
			.setMessage(R.string.on_mobile_expl)
			.setPositiveButton(R.string.yes, listener)
			.setNegativeButton(R.string.no, null)
			.create();
			
			// if we're on a mobile network and the setting is on, show warning
			if (prefs.getBoolean("XfDroid.mobileWarnings", true) && 
					cm.getActiveNetworkInfo().getType() == 0)
				ad.show();
			else
				showScreenshotsFor(f);
			return true;
		}
		return false;
	}

	private void showScreenshotsFor(Friend f) {
		Intent i = new Intent(this, Screenshots.class);
		i.putExtra("nickname", f.getNick());
		startActivity(i);
		
		FriendEvent rie = new FriendEvent(XfireEvent.XF_REQINFO, f);
		EventManager.fireEvent(rie);
	}
	
	protected void onListItemClick(ListView l, View v, int position, long id) {
		Friend f = adapter.getItem(position);
		Intent i = new Intent(this, ConvoWindow.class);
		i.putExtra("friend", f.getUserid());
		startActivity(i);
		
		super.onListItemClick(l, v, position, id);
	}
		
	private void showBrowserFor(String url) {
		Uri uri = Uri.parse(url);
		Intent i = new Intent(Intent.ACTION_VIEW, uri);
		startActivity(i);
	}
	
	private void showSetStatusDialog(String statustext, boolean checked) {
		DialogInterface.OnClickListener listener =
			new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					CheckBox cb = (CheckBox)ad.findViewById(R.id.cbAfk);
					if(cb.isChecked()) {
						xfc.setStatusText("(AFK) " + getString(R.string.afk));
					} else {
						EditText et = (EditText)ad.findViewById(R.id.etStatusText);
						xfc.setStatusText(et.getText().toString());
					}
					setupTitle();
				}
			};
		
		DialogInterface.OnClickListener clearListener =
			new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					xfc.setStatusText("Online");
					setupTitle();
				}
			};
		
		View v = getLayoutInflater().inflate(R.layout.setstatus_dialog, null);
		
		ad = new AlertDialog.Builder(this)
		.setView(v)
		.setPositiveButton(R.string.ok, listener)
		.setNeutralButton(R.string.reset_status, clearListener)
		.setTitle(R.string.set_status)
		.create();
		ad.show();

		OnCheckedChangeListener checkedListener =
			new OnCheckedChangeListener() {
				public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
					EditText etStatusText =
						(EditText)ad.findViewById(R.id.etStatusText);
					etStatusText.setEnabled(!isChecked);
				}
			};
		
		CheckBox cb = (CheckBox)ad.findViewById(R.id.cbAfk);
		cb.setOnCheckedChangeListener(checkedListener);
		cb.setChecked(checked);
		
		EditText et = (EditText)ad.findViewById(R.id.etStatusText);
		et.setText(statustext);
	}
	
	private void showSetNickDialog(String nick) {
		DialogInterface.OnClickListener listener =
			new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
                    EditText etNickname =
                        (EditText)ad.findViewById(R.id.etNickname);
                    xfc.setNickname(etNickname.getText().toString());
                    setupTitle();
				}
			};
			
		View v = getLayoutInflater().inflate(R.layout.setnick_dialog, null);
		
		ad = new AlertDialog.Builder(this)
		.setView(v)
		.setPositiveButton(R.string.ok, listener)
		.setTitle(R.string.new_nickname)
		.create();
		
		ad.show();
		((EditText)ad.findViewById(R.id.etNickname)).setText(nick);
	}
	
	public void handleEvent(XfireEvent event) {
		Intent i = new Intent(this, Login.class);
		
		switch(event.getEventType()) {
		case XfireEvent.XF_DCREASON:
			i.putExtra("dcReason", true);
		case XfireEvent.XF_OFFLINE:
			startActivity(i);
			finish();
			return;
		case XfireEvent.XF_FRSTATUS:
		case XfireEvent.XF_FRGAME:
		case XfireEvent.XF_FRSTATUSTEXT:
			friendslistHandler.sendEmptyMessage(0);
			return;
		}
	}
	
	private Handler friendslistHandler = new Handler() {
		public void handleMessage(Message m) {
			adapter.sort(new FriendComparator());
			adapter.notifyDataSetChanged();
			setupTitle();
		}
	};
	
	private class FriendslistAdapter extends ArrayAdapter<Friend> {
		public FriendslistAdapter(Context context, int textViewResourceId,
				List<Friend> objects) {
			super(context, textViewResourceId, objects);
		}

		
		
		public View getView(int position, View convertView, ViewGroup parent) {
			View v = convertView;
            if (v == null) {
                LayoutInflater li = (LayoutInflater)getSystemService(
                                Context.LAYOUT_INFLATER_SERVICE);
                v = li.inflate(R.layout.friendrow, null);
            }
            
            Friend f = getItem(position);
            
            TextView nick = (TextView)v.findViewById(R.id.tvNickname);
            TextView statustext = (TextView)v.findViewById(R.id.tvStatusText);
            ImageView imageview = (ImageView)v.findViewById(R.id.ivImage);
            
            nick.setText(f.getNick());
            statustext.setText(f.getStatusText());
            
            byte[] image = f.getImage();
            if (image != null) {
            	Bitmap bm = BitmapFactory.decodeByteArray(image, 0, image.length);
            	imageview.setImageBitmap(bm);
            } else
            	imageview.setImageResource(R.drawable.unknown);
            
            return v;
		}		
	}
}
